package com.zhiche.wms.service.surpports.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.collect.Maps;
import com.zhiche.wms.core.supports.BaseException;
import com.zhiche.wms.core.supports.enums.TableStatusEnum;
import com.zhiche.wms.core.utils.SnowFlakeId;
import com.zhiche.wms.domain.model.inbound.InboundNoticeLine;
import com.zhiche.wms.domain.model.inbound.InboundPutawayHeader;
import com.zhiche.wms.domain.model.inbound.InboundPutawayLine;
import com.zhiche.wms.domain.model.log.ItfImplogHeader;
import com.zhiche.wms.domain.model.otm.OtmOrderRelease;
import com.zhiche.wms.domain.model.outbound.OutboundNoticeLine;
import com.zhiche.wms.domain.model.outbound.OutboundPrepareHeader;
import com.zhiche.wms.domain.model.outbound.OutboundShipHeader;
import com.zhiche.wms.service.constant.PutAwayType;
import com.zhiche.wms.service.constant.SourceSystem;
import com.zhiche.wms.service.inbound.IInboundNoticeLineService;
import com.zhiche.wms.service.inbound.IInboundPutawayHeaderService;
import com.zhiche.wms.service.log.IItfImplogHeaderService;
import com.zhiche.wms.service.otm.IOtmOrderReleaseService;
import com.zhiche.wms.service.outbound.IOutboundNoticeLineService;
import com.zhiche.wms.service.outbound.IOutboundPrepareHeaderService;
import com.zhiche.wms.service.outbound.IOutboundShipLineService;
import com.zhiche.wms.service.surpports.IHnInterfaceService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class HnInterfaceServiceImpl implements IHnInterfaceService {
    private static final Logger LOGGER = LoggerFactory.getLogger(HnInterfaceServiceImpl.class);

    @Autowired
    private IOtmOrderReleaseService releaseService;
    @Autowired
    private IInboundNoticeLineService inboundNoticeLineService;
    @Autowired
    private IInboundPutawayHeaderService putawayHeaderService;
    @Autowired
    private SnowFlakeId flakeId;
    @Autowired
    private IItfImplogHeaderService implogHeaderService;
    @Autowired
    private IOutboundNoticeLineService outboundNoticeLineService;
    @Autowired
    private IOutboundShipLineService shipLineService;
    @Autowired
    private IOutboundPrepareHeaderService prepareHeaderService;

    /**
     * 霍尼扫码入库
     */
    @Override
    public HashMap<String, Object> updateInboundCar(Map<String, String> condition) {
        if (condition == null || condition.isEmpty()) {
            throw new BaseException("参数不能为空");
        }
        String key = condition.get("key");
        String houseId = condition.get("houseId");
        if (StringUtils.isBlank(houseId)) {
            throw new BaseException("仓库id不能为空");
        }
        if (StringUtils.isBlank(key)) {
            throw new BaseException("二维码/车架号不能为空");
        }
        new Thread(() -> {
            ItfImplogHeader ilh = new ItfImplogHeader();
            ilh.setId(flakeId.nextId());
            ilh.setLineCount(0);
            ilh.setStatus(TableStatusEnum.STATUS_10.getCode());
            ilh.setType(TableStatusEnum.STATUS_10.getCode());
            ilh.setRemarks("霍尼自动入库接口");
            ilh.setImportTime(new Date());
            ilh.setDataContent(JSONObject.toJSONString(condition));
            implogHeaderService.insert(ilh);
        }).start();

        EntityWrapper<OtmOrderRelease> ew = new EntityWrapper<>();
        ew.ne("status", TableStatusEnum.STATUS_50.getCode())
                .andNew()
                .eq("qr_code", key)
                .or()
                .eq("vin", key)
                .orderBy("id", false);
        List<OtmOrderRelease> releases = releaseService.selectList(ew);
        EntityWrapper<InboundNoticeLine> inEW = new EntityWrapper<>();
        if (CollectionUtils.isEmpty(releases)) {
            inEW.eq("lot_no1", key);
        } else {
            inEW.eq("lot_no1", releases.get(0).getVin());
        }
        inEW.eq("store_house_id", houseId);
        inEW.orderBy("id", false);
        //防止全表查  增加page
        Page<InboundNoticeLine> page = new Page<>();

        List<InboundNoticeLine> lines = inboundNoticeLineService.pageInboundNotice(page, inEW);
        if (CollectionUtils.isEmpty(lines)) {
            throw new BaseException("未查询到key:" + key + "的入库信息");
        }
        String status = lines.get(0).getStatus();
        if (TableStatusEnum.STATUS_50.getCode().equals(status)) {
            LOGGER.info("通知单id{}车辆已经取消", lines.get(0).getId());
            throw new BaseException("车架号:" + lines.get(0).getLotNo1() + "已经取消");
        }
        if (TableStatusEnum.STATUS_30.getCode().equals(status)) {
            LOGGER.info("通知单id{}车辆已经入库", lines.get(0).getId());
            throw new BaseException("通知单id:" + lines.get(0).getLotNo1() + "车辆已经入库");
        }
        //调用入库
        InboundPutawayHeader header = putawayHeaderService.updateByNoticeLineId(lines.get(0).getId(),
                PutAwayType.NOTICE_PUTAWAY, SourceSystem.HONEYWELL, null);
        HashMap<String, Object> data = Maps.newHashMap();
        InboundPutawayLine line = header.getInboundPutawayLineList().get(0);
        String locationNo = line.getLocationNo();
        data.put("locDetail", locationNo);
        data.put("vin", line.getLotNo1());
        return data;
    }

    /**
     * 重构 霍尼扫码自动出库
     */
    @Override
    public HashMap<String, Object> updateOutBoundCar(Map<String, String> condition) {
        if (condition == null || condition.isEmpty()) {
            throw new BaseException("参数不能为空");
        }
        String key = condition.get("key");
        String houseId = condition.get("houseId");
        if (StringUtils.isBlank(houseId)) {
            throw new BaseException("仓库id不能为空");
        }
        if (StringUtils.isBlank(key)) {
            throw new BaseException("二维码/车架号不能为空");
        }
        new Thread(() -> {
            ItfImplogHeader ilh = new ItfImplogHeader();
            ilh.setId(flakeId.nextId());
            ilh.setLineCount(0);
            ilh.setStatus(TableStatusEnum.STATUS_10.getCode());
            ilh.setType(TableStatusEnum.STATUS_20.getCode());
            ilh.setRemarks("霍尼自动出库接口");
            ilh.setImportTime(new Date());
            ilh.setDataContent(JSONObject.toJSONString(condition));
            implogHeaderService.insert(ilh);
        }).start();

        EntityWrapper<OtmOrderRelease> ew = new EntityWrapper<>();
        ew.ne("status", TableStatusEnum.STATUS_50.getCode())
                .andNew()
                .eq("qr_code", key)
                .or()
                .eq("vin", key)
                .orderBy("id", false);
        List<OtmOrderRelease> releases = releaseService.selectList(ew);
        EntityWrapper<OutboundNoticeLine> outEW = new EntityWrapper<>();
        if (CollectionUtils.isEmpty(releases)) {
            outEW.eq("lot_no1", key);
        } else {
            outEW.eq("lot_no1", releases.get(0).getVin());
        }
        outEW.eq("store_house_id", houseId);
        outEW.orderBy("id", false);
        Page<OutboundNoticeLine> page = new Page<>();
           List<OutboundNoticeLine> lines = outboundNoticeLineService.pageOutboundNotice(page,outEW);

        if (CollectionUtils.isEmpty(lines)) {
            throw new BaseException("未查询到key:" + key + "的入库信息");
        }
        OutboundNoticeLine noticeLine = lines.get(0);
        String status = noticeLine.getStatus();
        if (TableStatusEnum.STATUS_50.getCode().equals(status)) {
            LOGGER.info("通知单id{}车辆已经取消",noticeLine.getId());
            throw new BaseException("车架号:" + noticeLine.getLotNo1() + "已经取消");
        }
        if (TableStatusEnum.STATUS_30.getCode().equals(status)) {
            LOGGER.info("通知单id{}车辆已经出库",noticeLine.getId());
            throw new BaseException("车架号:" + noticeLine.getLotNo1() + "已经出库");
        }
        OutboundShipHeader shipHeader = shipLineService.shipByNoticeLineId(noticeLine.getId(), PutAwayType.NOTICE_PUTAWAY, SourceSystem.HONEYWELL);
        EntityWrapper<OutboundPrepareHeader> outPreHeaderEW = new EntityWrapper<>();
        outPreHeaderEW.eq("notice_id", shipHeader.getNoticeId())
                .ne("status", TableStatusEnum.STATUS_50.getCode())
                .orderBy("id", false);
        OutboundPrepareHeader prepareHeader = prepareHeaderService.selectOne(outPreHeaderEW);
        //返回装车道
        HashMap<String, Object> result = Maps.newHashMap();
        result.put("locDetail", prepareHeader == null ? null : prepareHeader.getLoadingArea());
        result.put("vin", noticeLine.getLotNo1());
        return result;
    }
}
